import { ref, watchEffect } from 'vue'
import { useRoute } from 'vue-router'
import { getBlogList } from '@/api/blogApi'

function useGetBlogList(opt = {}) {
  const { my = false } = opt
  // 定义 list total
  const list = ref([])
  const total = ref(0)
  const currentPage = ref(1)
  const pageSizeRef = ref(10)

  const $route = useRoute()

  const getBlogListFn = async () => {
    const query = $route.query
    currentPage.value = Number(query.page) || 1
    pageSizeRef.value = Number(query.pageSize) || 10

    const page = Number(query.page) || 1
    const pageSize = Number(query.pageSize) || 10
    const category = query.category || ''
    const keyword = query.keyword || ''
    const res = await getBlogList({ page, pageSize, category, keyword, my })
    list.value = res.list
    total.value = res.total
  }

  // 使用 watchEffect监听url参数page、pageSize、category、keyword的变化，然后调用获取博客列表的接口
  watchEffect(getBlogListFn)

  return { list, total, currentPage, pageSizeRef, getBlogListFn }
}

export default useGetBlogList
